package com.zhanghe.im.handler;

import com.zhanghe.im.request.ListGroupMemberRequestPacket;
import com.zhanghe.im.response.ListGroupMemberResponsePacket;
import com.zhanghe.im.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.ArrayList;
import java.util.List;

public class SimpleListGroupRequestHandler extends SimpleChannelInboundHandler<ListGroupMemberRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ListGroupMemberRequestPacket msg) throws Exception {
        String groupId = msg.getGroupId();

        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        ListGroupMemberResponsePacket listGroupMemberResponsePacket = new ListGroupMemberResponsePacket();
        if(channelGroup!=null){
            List<String> users = new ArrayList<>();
            for(Channel channel:channelGroup){
                String userName = SessionUtil.getSession(channel).getUserName();
                users.add(userName);
            }
            listGroupMemberResponsePacket.setSuccess(true);
            listGroupMemberResponsePacket.setGroupId(groupId);
            listGroupMemberResponsePacket.setUsers(users);
        }else{
            listGroupMemberResponsePacket.setSuccess(false);
            listGroupMemberResponsePacket.setMsg("不存在的群");
        }
        ctx.channel().writeAndFlush(listGroupMemberResponsePacket);
    }
}
